<?php

namespace frontend\modules\business\controllers\user;

use common\components\Upload;
use common\models\business\BusinessPig;
use common\models\shop\ShopComment;
use common\models\shop\ShopGoods;
use common\models\shop\ShopOrder;
use common\models\shop\ShopOrderGoods;
use common\models\shop\ShopUserAddress;
use common\models\sys\SysSetting;
use frontend\controllers\BaseMobileController;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;


/**
 * 仅仅为了兼容以前生成的二维码，做跳转用的
 */
class PorkOrderController extends BaseMobileController
{


    /**
     * @return string
     * 猪肉订单
     */
    public function actionIndex()
    {
        $status = \Yii::$app->request->get('status');
        if(!is_null($status) && $status == 5){
            $orderlist = ShopOrder::find()
                ->alias('o')
                ->select('o.ordersn as no,o.id,o.status,o.price,o.createtime,o.sendtype')
                ->where('o.userid=:userid and o.status>=0 and o.status in(5,6,7)',[':userid'=>$this->user['userid']])
                ->asArray()
                ->orderBy('status')
                ->all();
        }else if(!is_null($status)){
            $orderlist = ShopOrder::find()
                ->alias('o')
                ->select('o.ordersn as no,o.id,o.status,o.price,o.createtime,o.sendtype')
                ->where('o.userid=:userid and o.status>=0 and o.status=:status',[':userid'=>$this->user['userid'],':status'=>\Yii::$app->request->get('status')])
                ->asArray()
                ->orderBy('status')
                ->all();
        }else{
            $orderlist = ShopOrder::find()
                ->alias('o')
                ->select('o.ordersn as no,o.id,o.status,o.price,o.createtime,o.sendtype')
                ->where('o.userid=:userid and o.status>=0 ',[':userid'=>$this->user['userid']])
                ->asArray()
                ->orderBy('status')
                ->all();
        }

        foreach ($orderlist as $key => $row){
            $goods = \Yii::$app->db->createCommand('select og.iscomment,g.id,g.title,g.thumb as img,og.total as num,og.price from '.ShopOrderGoods::tableName().' as og left join '.ShopGoods::tableName().' as g on g.id=og.goodsid where og.orderid=:oid')
            ->bindValues([':oid'=> $row['id']])
            ->queryAll();
            $totalnum = 0;
            $i = 0;
            foreach($goods as $k => $r){
                if($r['iscomment']){
                    $i++;
                }
                $goods[$k]['img'] = Upload::checkGetUrl($r['img']);
                $totalnum += $r['num'];
            }
            //判断是否评价
            if($i == count($goods)){
                $orderlist[$key]['comment'] = 1;
            }else{
                $orderlist[$key]['comment'] = 0;
            }
            $orderlist[$key]['goods'] = $goods;
            $orderlist[$key]['oldstatus'] = $row['status'];
            $orderlist[$key]['status'] = ShopOrder::$statues[$row['status']];
            $orderlist[$key]['totalnum'] = $totalnum;
            $orderlist[$key]['totalprice'] = $row['price'];
            $orderlist[$key]['cost'] = $row['price'];
            $orderlist[$key]['urltype'] = 'olist';
        }

        return $this->render('@template/mobile/order_list.html',[
            'orderlist' => \GuzzleHttp\json_encode($orderlist),
            'status' => $status,
        ]);
    }


    /**
     * @return string
     * 待评价
     */
    public function actionWaitComment()
    {

        $orderid = \Yii::$app->request->get('id');

        $query = (new Query())->select(' g.id as goodsid,g.title,g.thumb as img,og.total as num,og.price,o.ordersn as no,o.id,o.status,o.createtime')
            ->from(ShopOrderGoods::tableName().' og')
            ->leftJoin(ShopGoods::tableName().' as g','og.goodsid=g.id')
            ->leftJoin(ShopOrder::tableName().' as o','o.id=og.orderid');

        if(is_null($orderid)){
            $goods = $query->where('o.status=:status and userid=:userid and iscomment=0',[':status'=>ShopOrder::STATUS_RECEIVE,':userid'=>$this->user['userid']])
                ->all();
        }else{
            $goods = $query->where('o.id=:id and iscomment=0',[':id'=>$orderid])
                ->all();
        }

        foreach ($goods as $key => $row) {
            $goods[$key]['oldstatus'] = $row['status'];
            $row['img'] = Upload::checkGetUrl($row['img']);
            $goods[$key]['goods'][] = $row;
            $goods[$key]['status'] = ShopOrder::$statues[$row['status']];
            $goods[$key]['totalnum'] = $row['num'];
            $goods[$key]['totalprice'] = $row['price']*$row['num'];
            $goods[$key]['cost'] = $row['price']*$row['num'];
            $goods[$key]['urltype'] = 'wait';
        }
        return $this->render('@template/mobile/order_list.html',[
            'orderlist' => \GuzzleHttp\json_encode($goods),
            'status' => ShopOrder::STATUS_RECEIVE
        ]);

    }



    /**
     * @return array
     * 取消订单
     */
    public function actionCancal()
    {
        $postdata = \Yii::$app->request->post();
         $res = \Yii::$app->db->createCommand()->update(ShopOrder::tableName(),['status'=>ShopOrder::STATUS_CANCAL],'id=:id',[':id'=>$postdata['id']])
             ->execute();

        //取出购买的商品
        $allgoods = (new Query())->select('g.title')
            ->from(ShopOrderGoods::tableName().' as og')
            ->leftJoin(ShopGoods::tableName().' as g','og.goodsid=g.id')
            ->where('og.orderid=:orderid',[':orderid' => $postdata['id']])
            ->all();
        //发送模板消息
        $titles = ArrayHelper::getColumn($allgoods,'title');
        $titles = implode(',',$titles);
        $data = [
            "first"  => "您购买的“".$titles."”；订单已取消",
            "keyword1"   => "取消订单提醒",
            "keyword2"  => date('Y-m-d H:i:s'),
            "remark" => "欢迎再次光临！",
        ];
        $notice = \Yii::$app->wechat->notice->to($this->user['openid'])
//            ->url(\Yii::$app->request->hostInfo.'/business/user/pork-order/index')
            ->template(SysSetting::getValue('template_msgid'))
            ->andData($data)
            ->send();


         return $res?$this->jsonMsg():$this->jsonMsg('取消失败',1);
    }



    /**
     * @return array
     * 申请退款
     */
    public function actionRefund()
    {
        $postdata = \Yii::$app->request->post();
        $res = \Yii::$app->db->createCommand()->update(ShopOrder::tableName(),['status'=>ShopOrder::STATUS_REFOUND],'id=:id',[':id'=>$postdata['id']])
            ->execute();

        return $res?$this->jsonMsg('提交退款申请成功，请等待审核'):$this->jsonMsg('退款申请失败',1);
    }


    /**
     * @return array
     * 确认收货
     */
    public function actionReceive()
    {
        $postdata = \Yii::$app->request->post();
        $res = \Yii::$app->db->createCommand()->update(ShopOrder::tableName(),['status'=>ShopOrder::STATUS_RECEIVE],'id=:id',[':id'=>$postdata['id']])
            ->execute();

        //取出购买的商品
        $allgoods = (new Query())->select('g.title')
            ->from(ShopOrderGoods::tableName().' as og')
            ->leftJoin(ShopGoods::tableName().' as g','og.goodsid=g.id')
            ->where('og.orderid=:orderid',[':orderid' => $postdata['id']])
            ->all();


        //发送模板消息
        $titles = ArrayHelper::getColumn($allgoods,'title');
        $titles = implode(',',$titles);
        $data = [
            "first"  => "您购买的“".$titles."”已经确认收货",
            "keyword1"   => "收货提醒",
            "keyword2"  => date('Y-m-d H:i:s'),
            "remark" => "欢迎再次光临！",
        ];
        $notice = \Yii::$app->wechat->notice->to($this->user['openid'])
            ->url(\Yii::$app->request->hostInfo.'/business/user/pork-order/wait-comment')
            ->template(SysSetting::getValue('template_msgid'))
            ->andData($data)
            ->send();


        return $res?$this->jsonMsg():$this->jsonMsg('网络异常',1);
    }






}